package com.cc8w.exception;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class MyGlobalExceptionHandler {
		
    private static final String ERROR_PAGE = "error";
    
    public static boolean isAjaxRequest(HttpServletRequest request) {
        return request.getHeader("x-requested-with") != null;
    }
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Object handleException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Exception e) throws UnsupportedEncodingException {
        if (isAjaxRequest(httpServletRequest)){
             //这里返回项目中自定义的统一响应对象即可
            return json(e);
        }
        return view(e);
    }

    //这里返回项目中自定义的统一响应对象即可
    private Object json(Exception e) {
        return e;
    }
 
        //这里返回 ModelAndView 
    public ModelAndView view(Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setStatus(HttpStatus.BAD_REQUEST);
        modelAndView.setViewName(ERROR_PAGE);
        modelAndView.addObject("msg","msg");
        modelAndView.addObject("code","code");
        System.out.println(HttpStatus.BAD_REQUEST);
        return modelAndView;
    }

}
